<template>
  <el-dialog
    :title="editable ? 'Edit' : 'Add'"
    :visible.sync="dialogVisible"
    width="25%"
    @close="handleClose"
  >
    <el-form
      ref="form"
      :model="dataForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="role name" prop="roleName">
        <el-input
          v-model="dataForm.roleName"
          style="width: 250px"
          maxlength="100"
          placeholder="enter role name please"
        />
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">Cancel</el-button>
      <el-button type="primary" @click="save">Save</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getRoleInfo, saveRole } from '@/api/role'
export default {
  data() {
    return {
      dialogVisible: false,
      editable: false,
      dataForm: {
        roleName: ''
      },
      rules: {
        roleName: [
          { required: true, message: 'role name is not null', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    /**
     * save the form
     */
    async save() {
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          const {
            id, roleName
          } = this.dataForm
          await saveRole({ id, roleName })
          this.$message({
            type: 'success',
            message: 'save success'
          })
          this.handleClose()
        }
      })
    },

    handleClose() {
      this.dialogVisible = false
      this.$refs.form.resetFields()
      this.dataForm = this.$options.data().dataForm
    },

    async show(id) {
      this.editable = !!id
      if (id) {
        const role = await getRoleInfo()
        Object.assign(this.dataForm, role)
      }
      this.dialogVisible = true
    }
  }
}
</script>
